﻿//-----------------------------------------------------------------------
// <copyright file="LinkedInConsumer.cs" company="Loqu8">
//     Copyright (c) Loqu8, Inc. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace DotNetOpenAuth.ApplicationBlock
{
    using System;
    using System.IO;
    using System.Net;
    using System.Xml.Linq;
    using DotNetOpenAuth.Messaging;
    using DotNetOpenAuth.OAuth;
    using DotNetOpenAuth.OAuth.ChannelElements;

    /// <summary>
    /// A consumer capable of communicating with LinkedIn Data APIs.
    /// </summary>
    public static class LinkedInConsumer
    {
        /// <summary>
        /// The Consumer to use for accessing LinkedIn data APIs.
        /// </summary>
        public static readonly ServiceProviderDescription ServiceDescription = new ServiceProviderDescription
        {
            RequestTokenEndpoint = new MessageReceivingEndpoint("https://api.linkedin.com/uas/oauth/requestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest),
            UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://api.linkedin.com/uas/oauth/authorize", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest),
            AccessTokenEndpoint = new MessageReceivingEndpoint("https://api.linkedin.com/uas/oauth/accessToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest),
            TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
        };

        private static readonly MessageReceivingEndpoint GetProfileEndpoint =
            new MessageReceivingEndpoint(
                "https://api.linkedin.com/v1/people/~",
                HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);

        private static readonly MessageReceivingEndpoint GetConnectionsEndpoint = 
            new MessageReceivingEndpoint(
                "https://api.linkedin.com/v1/people/~/connections",
                 HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);

        public static XDocument GetProfile(ConsumerBase consumer, string accessToken)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException("consumer");
            }

            var response = consumer.PrepareAuthorizedRequestAndSend(GetProfileEndpoint, accessToken);
            string body = response.GetResponseReader().ReadToEnd();
            XDocument result = XDocument.Parse(body);
            return result;
        }

        public static XDocument GetConnections(ConsumerBase consumer, string accessToken)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException("consumer");
            }

            try
            {
                var request = consumer.PrepareAuthorizedRequest(GetConnectionsEndpoint, accessToken);
                var response = request.GetResponse();

                StreamReader sr = new StreamReader(response.GetResponseStream());
                string body = sr.ReadToEnd();
                XDocument result = XDocument.Parse(body);
                return result;
            }
            catch (WebException ex)
            {
                Stream s = ex.Response.GetResponseStream();
                StreamReader sr = new StreamReader(s);

                // System.Windows.MessageBox.Show(sr.ReadToEnd());
                return null;
            }
            catch (Exception ex)
            {
                // System.Windows.MessageBox.Show(ex.Message + Environment.NewLine +
                    // ex.GetType().ToString() + Environment.NewLine +
                    // ex.StackTrace);
                return null;
            }
        }

        public static XDocument Search(ConsumerBase consumer, string accessToken, string keywords)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException("consumer");
            }

            try
            {
                var request = consumer.PrepareAuthorizedRequest(
                    new MessageReceivingEndpoint(
                        String.Format("https://api.linkedin.com/v1/people/?keywords={0}", keywords),
                        HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
                    accessToken);

                var response = request.GetResponse();

                StreamReader sr = new StreamReader(response.GetResponseStream());
                string body = sr.ReadToEnd();                
                XDocument result = XDocument.Parse(body);
                return result;
            }
            catch (WebException ex)
            {
                Stream s = ex.Response.GetResponseStream();
                StreamReader sr = new StreamReader(s);

                // System.Windows.MessageBox.Show(sr.ReadToEnd());
                return null;
            }
            catch (Exception ex)
            {
                // System.Windows.MessageBox.Show(ex.Message + Environment.NewLine +
                //    ex.GetType().ToString() + Environment.NewLine +
                //    ex.StackTrace);
                return null;
            }
        }
    }
}
